package com.corechina.apex_osswords.common;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Calendar;
import java.util.Date;

/**
 * @program: hdahms_mysql
 * @description: 日期操作工具类
 * @author: cc
 * @create: 2021-09-28 16:58
 **/
public class DateUtil {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static Calendar startDate = Calendar.getInstance();
    private static Calendar endDate = Calendar.getInstance();
    private static DateFormat df = DateFormat.getDateInstance();
    private static Date earlydate = new Date();
    private static Date latedate = new Date();

    /**
     * 计算两个时间相差多少个年
     */
    public static int yearsBetween(LocalDate start, LocalDate end) {
        Period period = Period.between(start, end);
        return period.getYears();
    }

    /**
     * 计算两个时间相差多少个月
     */
    public static int monthsBetween(LocalDate start, LocalDate end) {
        Period period = Period.between(start, end);
        return period.getMonths();

    }

    /**
     * 计算两个时间相差多少个天
     */
    public static int daysBetween(LocalDate start, LocalDate end) {
        // 得到两个日期相差多少天
        long days = end.toEpochDay() - start.toEpochDay();
        return (int) days;
    }

    /**
     * 计算两个时间相差多少小时
     */
    public static int hoursBetween(String start, String end) throws ParseException {
        // 得到两个日期相差多少小时
        return minutesBetween(start, end) / 60;
    }

    /**
     * 计算两个时间相差多少分
     */
    public static int minutesBetween(String start, String end) throws ParseException {
        // 得到两个日期相差多少分
        return secondesBetween(start, end) / 60;
    }

    /**
     * 计算两个时间相差多少秒
     */
    public static int secondesBetween(String start, String end) throws ParseException {
        earlydate = df.parse(start);
        latedate = df.parse(end);
        startDate.setTime(earlydate);
        endDate.setTime(latedate);
        // 设置时间为0时
        startDate.set(Calendar.HOUR_OF_DAY, 0);
        startDate.set(Calendar.MINUTE, 0);
        startDate.set(Calendar.SECOND, 0);
        endDate.set(Calendar.HOUR_OF_DAY, 0);
        endDate.set(Calendar.MINUTE, 0);
        endDate.set(Calendar.SECOND, 0);
        // 得到两个日期相差多少秒
        return ((int) (endDate.getTime().getTime() / 1000) - (int) (startDate.getTime().getTime() / 1000));
    }

}
